import { debounceTime, first } from 'rxjs/operators';
import { Component, OnDestroy, OnInit, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import { BaseFieldComponent } from '../base-field/base-field.component';
// import '../../../../../../../node_modules/@ckeditor/ckeditor5-build-inline/build/translations/zh_cn.js';
// import * as InlineEditor from '@ckeditor/ckeditor5-build-inline';
// import { ChangeEvent, CKEditorComponent } from '@ckeditor/ckeditor5-angular/ckeditor.component';
import { PermitConfig, PermitConfigId } from '../../../models';
import { EditorComponent } from '@tinymce/tinymce-angular';
import { Subscription } from 'rxjs';
import { Condition } from 'src/app/models';
// import { CKEditor5 } from '@ckeditor/ckeditor5-angular';
import { styleTool } from './style.tool';

@Component({
  selector: 'zepride-space-occupying',
  templateUrl: './space-occupying.component.html',
  styleUrls: ['./space-occupying.component.less', '../field.common.less']
})
export class SpaceOccupyingComponent extends BaseFieldComponent implements OnInit, AfterViewInit, OnDestroy {

  txtContent = '';
  // editorConfig: CKEditor5.Config = {
  //   toolbar:
  //     ['fontSize', '|', 'bold', 'italic', 'link', 'numberedList', 'bulletedList', 'mediaEmbed', 'insertTable', 'outdent', 'Indent', 'FontSize','JustifyLeft', 'JustifyCenter', 'JustifyRight', 'undo', 'redo'],
  //   language: "zh_cn"
  // };
  // Editor = InlineEditor;
  componentConditionChange$: Subscription;
  borderStyle: any;
  isAuthorized = true;
  permitConfig: PermitConfig[] = [
    { mode: 'query', permitId: '查看', permitName: '', authObjectId: '' },
    { mode: 'edit', permitId: '编辑', permitName: '', authObjectId: '' }
  ];
  options = {
    base_url: '/tinymce', // Root for resources
    suffix: '.min', // Suffix to use when loading resources
    min_height: 70,
    max_height: 680,
    menubar: false,
    table_default_attributes: {},
    table_default_styles: {},
    content_css: [],
    plugins: [
      'advlist autolink lists link image charmap print preview anchor',
      'searchreplace visualblocks code fullscreen',
      'insertdatetime media table paste code help wordcount'
    ],
    toolbar: 'undo redo | formatselect | bold italic backcolor | \
      alignleft aligncenter alignright alignjustify | \
      bullist numlist outdent indent | removeformat | help'
  };
  private contentEditRef: ElementRef<HTMLElement>;
  @ViewChild('contentEdit') set contentEdit(ref: ElementRef<HTMLElement>) {
    this.contentEditRef = ref;
  }
  private disabledContentRef: ElementRef<HTMLElement>;
  @ViewChild('disabledContent') set disabledContent(ref: ElementRef<HTMLElement>) {
    this.disabledContentRef = ref;
  }
  @ViewChild(EditorComponent) editorComponent: EditorComponent;
  @ViewChild('richText') richText: ElementRef<HTMLElement>;
  isWord = false;
  unassigned = true;
  defaultOptions = {
    fontFamily: '仿宋',
    lineHeight: '1.5',
    fontSize: 14
  };

  ngOnInit(): void {
    this.borderStyle = this.componentData.extends.border;
    this.isWord = this.componentData.extends.isWord;
    this.initEditorToolbar();
    setTimeout(() => {
      if (this.bindData) {
        this.txtContent = this.bindData;
      } else {
        this.replaceTxt();
      }
      this.setHtmlContent(this.txtContent);
      const authData = this.setAuthorityData();
      this.zeprideAuthorityData = {
        ...authData,
        afterChecked: this.afterAuthChecked.bind(this)
      };
    }, 200);
  }

  ngAfterViewInit() {
    this.registerModelChange();
    this.registerConditionChange();
  }

  setHtmlContent(content: string) {
    const containerEdit = this.contentEditRef;
    const disableContainer = this.disabledContentRef;
    const container = containerEdit ? containerEdit : disableContainer;
    if (this.isWord && container && container.nativeElement) {
      container.nativeElement.innerHTML = content;
    }
  }

  registerModelChange() {
    this.modelChange$ = this.engineService.dataModelChange$.pipe(
      debounceTime(50)
    ).subscribe(data => {
      if (data.identifyId !== this.componentData.identifyId) {
        this.txtContent = this.dataModel[this.componentData.bindField];
        this.replaceTxt();
      }
    });
  }

  private replaceTxt() {
    const spaceChars: any[] = this.componentData.extends.spaceChars;
    let txt: string = this.componentData.extends.txtAreaContent;
    if (!txt) {
      return;
    }
    for (const item of spaceChars) {
      // txt = this.componentData.extends.txtAreaContent;
      const indexNo = this.componentData.extends.indexNo;
      let repTxt = this.dataModel[item.bindField];
      if (indexNo != null && indexNo != undefined) {
        const key = Object.keys(this.dataModel).find(x => x.indexOf(`[${indexNo}].${item.bindField}`) > -1);
        if (!key) {
          continue;
        }
        const v = this.dataModel[key];
        if (v) {
          repTxt = v;
        }
      }
      repTxt || (repTxt = '【】');
      txt = txt.replace(item.code, repTxt);
    }
    txt = this.formatContent(txt);
    this.txtContent = txt;
    this.setData(this.txtContent);
    this.setHtmlContent(this.txtContent);
  }

  initEditorToolbar() {
    if (this.componentData.extends.toolBarShow && this.componentData.extends.toolBarShow === 'hide') {
      this.options.toolbar = false as any;
    }
  }

  onReady(editor) {
    if (this.componentData.extends.toolBarShow && this.componentData.extends.toolBarShow === 'show') {
      editor.ui.getEditableElement().parentElement.insertBefore(
        editor.ui.view.toolbar.element,
        editor.ui.getEditableElement()
      );
    }
  }

  onChange(params?: any) {
    let data: string;
    if (this.componentData.extends && this.componentData.extends.isWord) {
      const container = this.contentEditRef;
      if (container && container.nativeElement) {
        data = this.formatContent(container.nativeElement.innerHTML);
      }
    } else {
      data = params.editor.getContent();
    }
    // const htmlData = styleDom.outerHTML;
    this.txtContent = data;
    this.setBindData(this.txtContent);
  }

  formatContent(content: string) {
    if (!content) {
      return '';
    }
    if (!this.componentData.extends || !this.componentData.extends.isWord) {
      return content;
    }
    const container = document.createElement('div');
    container.innerHTML = content;
    const childNodes = container.childNodes;
    if (childNodes && childNodes.length) {
      const options = { ...this.defaultOptions, ...this.componentData.extends.contentStyle };
      options.width = '100%';
      childNodes.forEach((node: HTMLElement) => {
        styleTool(node, options);
      });
    }
    return container.innerHTML;
  }

  inputChange(value) {
    this.txtContent = value;
    this.setBindData(this.txtContent);
  }

  afterAuthChecked(params: {
    permitId: PermitConfigId;
    isAuthorized: boolean;
  }) {
    if (!params.isAuthorized) {
      this.isAuthorized = false;
      // this.editorConfig.readOnly = true;
    }
  }

  requestFullScreen() {
    let element: HTMLElement;
    if (this.componentData.extends && this.componentData.extends.isWord) {
      element = this.contentEditRef.nativeElement.parentElement;
    } else {
      const container = this.richText;
      if (container && container.nativeElement) {
        element = container.nativeElement.querySelector('.tox.tox-tinymce');
      }
    }
    if (element) {
      element.requestFullscreen();
    }
  }

  registerConditionChange() {
    this.componentConditionChange$ = this.engineService.componentConditionChange$.subscribe(condition => {
      this.onConditionChange(condition);
    });
  }

  onConditionChange(condition: Condition) {
    if (condition.objectId === this.componentData.tmpComItemId && this.componentData.bindField) {
      const field = this.componentData.bindField;
      if (condition.result) {
        // if (this.unassigned) {
        //   this.unassigned = false;
        // } else {
        this.replaceTxt();
        this.dataModel[field] = this.txtContent;
        // }
      }
    }
  }

  ngOnDestroy() {
    if (this.modelChange$) {
      this.modelChange$.unsubscribe();
    }
    if (this.componentConditionChange$) {
      this.componentConditionChange$.unsubscribe();
    }
  }
}
